#!/usr/bin/env bash
SYSTEMS='ac workflow buffalo camel cardbin dingo ecenter fitness fundcomm hippo macan polo rhino panther'

function setup_banner() {
cat <<'EOF' > /etc/motd
      ___            _
     / _ \_   ___  ___)___
    / /_)/ | | \ \/ / / __|
   / ___/| |_| |>  <| \__ \
   \/     \__, /_/\_\_|___/
          |___/

A sandbox where you can play fire!
EOF

for sys in $SYSTEMS
do
    if [ -d /work/backends/${sys} ]; then
    cat <<EOF >> /etc/motd
To start $sys backend please run:
sh start_${sys}.sh

EOF
    fi
done

cat <<'EOF' >> /etc/motd
then in another window run:
sh start_py.sh
Then point your browser to
http://pyxis.private.dev.pajkdc.com
And be a happy code monkey!!!

EOF
}

function enable_local_repo {
    # install PAJK internal devops rpm repo
    cat <<'EOF' > /etc/yum.repos.d/pajk.repo
[pajk]
name=PAJK devops repo
baseurl=http://10.255.136.32/yum/rhel/$releasever
enabled=1
gpgcheck=0

EOF
}

function setup_node() {
    curl -sL https://rpm.nodesource.com/setup | bash -
    yum install -y nodejs gcc-c++ make
    npm install -g bower http-server
}

function setup_nginx() {
    # install nginx
    yum install -y nginx
    chkconfig --level 345 nginx on
    service nginx start
}

function setup_vsftpd() {
    # install vsftpd
    yum install -y vsftpd
    chkconfig --level 345 vsftpd on
    sed -i 's/^#local_enable/local_enable/' /etc/vsftpd/vsftpd.conf
    sed -i 's/^#write_enable/write_enable/' /etc/vsftpd/vsftpd.conf
    service vsftpd start
}

function harden_mysql() {
    cat <<'EOF' | mysql -uroot
delete from mysql.user where user = '';
flush privileges;
EOF
}

function setup_mysql() {
    # install mysql
    yum install -y mysql-community-server
    chkconfig --level 345 mysqld on
    service mysqld start
    harden_mysql
}

function setup_redis() {
    yum install -y redis
    chkconfig redis on
    sed -i -e 's|^bind|#bind|' /etc/redis.conf
    service redis start
}

function setup_postgis() {
    yum install -y postgis2_94 postgresql94-server postgresql94-contrib
    service postgresql-9.4 initdb
    chkconfig postgresql-9.4 on
    cat <<EOF > /var/lib/pgsql/9.4/data/pg_hba.conf
local   all             all                                     trust
host    all             all             0.0.0.0/0               trust
EOF
    service postgresql-9.4 start
}

function setup_maven() {
    # setup internal maven repository
    if [[ ! -f /home/devel/.m2/settings.xml ]]; then
        [ -d /home/devel/.m2 ] || mkdir /home/devel/.m2
        mv /tmp/settings.xml /home/devel/.m2
        chown -R devel:devel /home/devel/.m2
    fi
}

function setup_pre_requisite_softwares() {
    # enable local repo to speedup mysql/pg/nginx/node setup
    enable_local_repo

    # check if epel repo is enabled
    rpm -q                                           \
        --queryformat "%{name} %{version} installed" \
        epel-release
    if [[  $? != 0 ]]; then
        yum install -y epel-release
    fi

    # check if mysql-server is installed
    rpm -q                                           \
        --queryformat "%{name} %{version} installed" \
        mysql-community-server
    if [[  $? != 0 ]]; then
        setup_mysql
    fi

    if [ -d /work/backends/camel ]; then
        # check if vsftpd is installed
        rpm -q                                           \
            --queryformat "%{name} %{version} installed" \
            vsftpd
        if [[  $? != 0 ]]; then
            setup_vsftpd
        fi

        # check if postgreSQL is installed
        rpm -q                                           \
            --queryformat "%{name} %{version} installed" \
            postgresql94
        if [[  $? != 0 ]]; then
            setup_postgis
        fi
        # check if postgis is installed
        rpm -q                                           \
            --queryformat "%{name} %{version} installed" \
            postgis2_94
        if [[  $? != 0 ]]; then
            setup_postgis
        fi
    fi

    if [ -d /work/backends/fitness ]; then
        # check if redis is installed
        rpm -q                                           \
            --queryformat "%{name} %{version} installed" \
            redis
        if [[  $? != 0 ]]; then
            setup_redis
        fi
    fi

    # check if nginx is installed
    rpm -q --queryformat "%{name} %{version} installed" nginx
    if [[  $? != 0 ]]; then
        setup_nginx
    fi

    # check if nodejs is installed
    rpm -q --queryformat "%{name} %{version} installed" nodejs
    if [[  $? != 0 ]]; then
        setup_node
    fi

    setup_maven
}

function setup_pyxis() {
    if [[  ! -f /etc/nginx/conf.d/pyxis.conf ]]; then
    cp /tmp/pyxis.conf /etc/nginx/conf.d/
    fi
}

function setup_webserver() {
    conf_file=$1
    if [[  ! -f /etc/nginx/conf.d/$conf_file ]]; then
        cp /tmp/$conf_file /etc/nginx/conf.d/
    fi
}

function setup_startup_scripts() {
    if [[ -d /work/backends/cardbin && ! -f /home/devel/debug_cardbin.sh ]]; then
    cat <<EOF > /home/devel/debug_cardbin.sh
cd /work/backends/cardbin/service-facade
mvn install
cd /work/backends/cardbin/service-impl
mvn -Drun.jvmArguments="-Xdebug -Xrunjdwp:transport=dt_socket,address=9555,server=y,suspend=n" spring-boot:run
EOF
    chown devel:devel /home/devel/debug_cardbin.sh
    fi


    if [[ -d /work/backends/cardbin && ! -f /home/devel/start_cardbin.sh ]]; then
    cat <<EOF > /home/devel/start_cardbin.sh
cd /work/backends/cardbin/service-facade
mvn install
cd /work/backends/cardbin/service-impl
mvn spring-boot:run
EOF
    chown devel:devel /home/devel/start_cardbin.sh
    fi

    if [[ -d /work/backends/camel && ! -f /home/devel/debug_camel.sh ]]; then
    cat <<EOF > /home/devel/debug_camel.sh
cd /work/backends/camel/camel-client
mvn install
cd /work/backends/camel/camel-core
mvn -Drun.jvmArguments="-Xdebug -Xrunjdwp:transport=dt_socket,address=9555,server=y,suspend=n" spring-boot:run
EOF
    chown devel:devel /home/devel/debug_camel.sh
    fi

    if [[ -d /work/backends/camel && ! -f /home/devel/start_camel.sh ]]; then
    cat <<EOF > /home/devel/start_camel.sh
cd /work/backends/camel/camel-client
mvn install
cd /work/backends/camel/camel-core
mvn spring-boot:run
EOF
    chown devel:devel /home/devel/start_camel.sh
    fi

    if [[ -d /work/backends/ecenter && ! -f /home/devel/debug_ecenter.sh ]]; then
    cat <<EOF > /home/devel/debug_ecenter.sh
cd /work/backends/ecenter/ecenter-client
mvn install
cd /work/backends/ecenter/ecenter-core
mvn -Drun.jvmArguments="-Xdebug -Xrunjdwp:transport=dt_socket,address=9555,server=y,suspend=n" spring-boot:run
EOF
    chown devel:devel /home/devel/debug_ecenter.sh
    fi

    if [[ -d /work/backends/ecenter && ! -f /home/devel/start_ecenter.sh ]]; then
    cat <<EOF > /home/devel/start_ecenter.sh
cd /work/backends/ecenter/ecenter-client
mvn install
cd /work/backends/ecenter/ecenter-core
mvn spring-boot:run
EOF
    chown devel:devel /home/devel/start_ecenter.sh
    fi

    if [[ -d /work/backends/rhino && ! -f /home/devel/debug_rhino.sh ]]; then
    cat <<EOF > /home/devel/debug_rhino.sh
cd /work/backends/rhino/rhino-api
mvn install
cd /work/backends/rhino/rhino-impl
mvn -Drun.jvmArguments="-Xdebug -Xrunjdwp:transport=dt_socket,address=9555,server=y,suspend=n" spring-boot:run
EOF
    chown devel:devel /home/devel/debug_rhino.sh
    fi

    if [[ -d /work/backends/rhino && ! -f /home/devel/start_rhino.sh ]]; then
    cat <<EOF > /home/devel/start_rhino.sh
cd /work/backends/rhino/rhino-api
mvn install
cd /work/backends/rhino/rhino-impl
mvn spring-boot:run
EOF
    chown devel:devel /home/devel/start_rhino.sh
    fi

    if [[ -d /work/backends/fundcomm && ! -f /home/devel/debug_fundcomm.sh ]]; then
    cat <<EOF > /home/devel/debug_fundcomm.sh
cd /work/backends/fundcomm/fundcommon-client
mvn -Dmaven.test.skip=true install
cd /work/backends/fundcomm/fundcommon-core
mvn -Drun.jvmArguments="-Xdebug -Xrunjdwp:transport=dt_socket,address=9555,server=y,suspend=n" spring-boot:run
EOF
    chown devel:devel /home/devel/debug_fundcomm.sh
    fi

    if [[ -d /work/backends/fundcomm && ! -f /home/devel/start_fundcomm.sh ]]; then
    cat <<EOF > /home/devel/start_fundcomm.sh
cd /work/backends/fundcomm/fundcommon-client
mvn -Dmaven.test.skip=true install
cd /work/backends/fundcomm/fundcommon-core
mvn spring-boot:run
EOF
    chown devel:devel /home/devel/start_fundcomm.sh
    fi

    if [[ -d /work/backends/polo && ! -f /home/devel/debug_polo.sh ]]; then
    cat <<EOF > /home/devel/debug_polo.sh
cd /work/backends/polo/polo-client
mvn -Dmaven.test.skip=true install
cd /work/backends/polo/polo-core
mvn -Drun.jvmArguments="-Xdebug -Xrunjdwp:transport=dt_socket,address=9555,server=y,suspend=n" spring-boot:run
EOF
    chown devel:devel /home/devel/debug_polo.sh
    fi

    if [[ -d /work/backends/polo && ! -f /home/devel/start_polo.sh ]]; then
    cat <<EOF > /home/devel/start_polo.sh
cd /work/backends/polo/polo-client
mvn -Dmaven.test.skip=true install
cd /work/backends/polo/polo-core
mvn spring-boot:run
EOF
    chown devel:devel /home/devel/start_polo.sh
    fi

    if [[ -d /work/backends/macan &&  ! -f /home/devel/debug_macan.sh ]]; then
    cat <<EOF > /home/devel/debug_macan.sh
cd /work/backends/macan/macan-client
mvn -Dmaven.test.skip=true install
cd /work/backends/macan/macan-core
mvn -Drun.jvmArguments="-Xdebug -Xrunjdwp:transport=dt_socket,address=9555,server=y,suspend=n" spring-boot:run
EOF
    chown devel:devel /home/devel/debug_macan.sh
    fi

    if [[ -d /work/backends/macan &&  ! -f /home/devel/start_macan.sh ]]; then
    cat <<EOF > /home/devel/start_macan.sh
cd /work/backends/macan/macan-client
mvn -Dmaven.test.skip=true install
cd /work/backends/macan/macan-core
mvn spring-boot:run
EOF
    chown devel:devel /home/devel/start_macan.sh
    fi

    if [[ -d /work/backends/hippo &&  ! -f /home/devel/debug_hippo.sh ]]; then
    cat <<EOF > /home/devel/debug_hippo.sh
cd /work/backends/hippo/hippo-api
mvn -Dmaven.test.skip=true install
cd /work/backends/hippo/hippo-impl
mvn -Drun.jvmArguments="-Xdebug -Xrunjdwp:transport=dt_socket,address=9555,server=y,suspend=n" spring-boot:run
EOF
    chown devel:devel /home/devel/debug_hippo.sh
    fi

    if [[ -d /work/backends/hippo &&  ! -f /home/devel/start_hippo.sh ]]; then
    cat <<EOF > /home/devel/start_hippo.sh
cd /work/backends/hippo/hippo-api
mvn -Dmaven.test.skip=true install
cd /work/backends/hippo/hippo-impl
mvn spring-boot:run
EOF
    chown devel:devel /home/devel/start_hippo.sh
    fi

    if [[ -d /work/backends/dingo &&  ! -f /home/devel/debug_dingo.sh ]]; then
    cat <<EOF > /home/devel/debug_dingo.sh
cd /work/backends/dingo/dingo-api
mvn -Dmaven.test.skip=true install
cd /work/backends/dingo/dingo-impl
mvn -Drun.jvmArguments="-Xdebug -Xrunjdwp:transport=dt_socket,address=9555,server=y,suspend=n" spring-boot:run
EOF
    chown devel:devel /home/devel/debug_dingo.sh
    fi

    if [[ -d /work/backends/dingo &&  ! -f /home/devel/start_dingo.sh ]]; then
    cat <<EOF > /home/devel/start_dingo.sh
cd /work/backends/dingo/dingo-api
mvn -Dmaven.test.skip=true install
cd /work/backends/dingo/dingo-impl
mvn spring-boot:run
EOF
    chown devel:devel /home/devel/start_dingo.sh
    fi

    if [[ -d /work/backends/fitness &&  ! -f /home/devel/debug_fitness.sh ]]; then
    cat <<EOF > /home/devel/debug_fitness.sh
cd /work/backends/fitness/fitness-api
mvn -Dmaven.test.skip=true install
cd /work/backends/fitness/fitness-impl
mvn -Drun.jvmArguments="-Xdebug -Xrunjdwp:transport=dt_socket,address=9555,server=y,suspend=n" spring-boot:run
EOF
    chown devel:devel /home/devel/debug_fitness.sh
    fi

    if [[ -d /work/backends/fitness &&  ! -f /home/devel/start_fitness.sh ]]; then
    cat <<EOF > /home/devel/start_fitness.sh
cd /work/backends/fitness/fitness-api
mvn -Dmaven.test.skip=true install
cd /work/backends/fitness/fitness-impl
mvn spring-boot:run
EOF
    chown devel:devel /home/devel/start_fitness.sh
   fi

   if [[ -d /work/backends/panther &&  ! -f /home/devel/debug_panther.sh ]]; then
    cat <<EOF > /home/devel/debug_panther.sh
cd /work/backends/panther/panther-api
mvn -Dmaven.test.skip=true install
cd /work/backends/panther/panther-impl
mvn -Drun.jvmArguments="-Xdebug -Xrunjdwp:transport=dt_socket,address=9555,server=y,suspend=n" spring-boot:run
EOF
    chown devel:devel /home/devel/debug_panther.sh
    fi

    if [[ -d /work/backends/panther &&  ! -f /home/devel/start_panther.sh ]]; then
    cat <<EOF > /home/devel/start_panther.sh
cd /work/backends/panther/panther-api
mvn -Dmaven.test.skip=true install
cd /work/backends/panther/panther-impl
mvn spring-boot:run
EOF
    chown devel:devel /home/devel/start_panther.sh
    fi

    if [[ -d /work/backends/buffalo &&  ! -f /home/devel/debug_buffalo.sh ]]; then
    cat <<EOF > /home/devel/debug_buffalo.sh
cd /work/backends/buffalo/buffalo-api
mvn -Dmaven.test.skip=true install
cd /work/backends/buffalo/buffalo-impl
mvn -Drun.jvmArguments="-Xdebug -Xrunjdwp:transport=dt_socket,address=9555,server=y,suspend=n" spring-boot:run
EOF
    chown devel:devel /home/devel/debug_buffalo.sh
    fi

    if [[ -d /work/backends/buffalo &&  ! -f /home/devel/start_buffalo.sh ]]; then
    cat <<EOF > /home/devel/start_buffalo.sh
cd /work/backends/buffalo/buffalo-api
mvn -Dmaven.test.skip=true install
cd /work/backends/buffalo/buffalo-impl
mvn spring-boot:run
EOF
    chown devel:devel /home/devel/start_buffalo.sh
    fi

    if [[ -d /work/backends/workflow && ! -f /home/devel/debug_workflow.sh ]]; then
    cat <<EOF > /home/devel/debug_workflow.sh
cd /work/backends/workflow/workflow-api
mvn install
cd /work/backends/workflow/workflow-impl
mvn -Drun.jvmArguments="-Xdebug -Xrunjdwp:transport=dt_socket,address=9555,server=y,suspend=n" spring-boot:run
EOF
    chown devel:devel /home/devel/debug_ac.sh
    fi

    if [[ -d /work/backends/workflow && ! -f /home/devel/start_workflow.sh ]]; then
       cat <<EOF > /home/devel/start_workflow.sh
cd /work/backends/workflow/workflow-api
mvn install
cd /work/backends/workflow/workflow-impl
mvn spring-boot:run
EOF
    chown devel:devel /home/devel/start_workflow.sh
    fi

    if [[ -d /work/backends/ac && ! -f /home/devel/debug_ac.sh ]]; then
    cat <<EOF > /home/devel/debug_ac.sh
cd /work/backends/ac/ac-client
mvn install
cd /work/backends/ac/ac-core
mvn -Drun.jvmArguments="-Xdebug -Xrunjdwp:transport=dt_socket,address=9555,server=y,suspend=n" spring-boot:run
EOF
    chown devel:devel /home/devel/debug_ac.sh
    fi

    if [[ -d /work/backends/ac && ! -f /home/devel/start_ac.sh ]]; then
       cat <<EOF > /home/devel/start_ac.sh
cd /work/backends/ac/ac-client
mvn install
cd /work/backends/ac/ac-core
mvn spring-boot:run
EOF
    chown devel:devel /home/devel/start_ac.sh
    fi

    if [[  ! -f /home/devel/start_py.sh ]]; then
    cat <<EOF > /home/devel/start_py.sh
cd /work/frontend
npm start
EOF
    chown devel:devel /home/devel/start_py.sh
    fi
}

function create_database_user() {
    user=$1
    passwd=$2
    got_user=$(echo "select 1 from user where user='$user'" | mysql -uroot -D mysql)
    if [[ ! -z $got_user ]]; then
         echo "drop user $user" | mysql -uroot
         echo "drop user $user@localhost" | mysql -uroot
    fi

    cat <<EOF | mysql -u root
create user '$user'@'%' identified by '$passwd';
create user '$user'@'localhost' identified by '';
grant file on *.* to '$user'@'%';
grant file on *.* to '$user'@'localhost';
EOF

}


function setup_database() {
    database=$1
    backend_dir=$2
    user=$3

    cat <<EOF | mysql -u root
drop database if exists $database;
create database if not exists $database
    default character set utf8
    default collate utf8_general_ci;
grant all privileges on $database.* to '$user'@'%';
grant all privileges on $database.* to '$user'@'localhost';
EOF

    # load schema if any
    if [[ -f /work/$backend_dir/schema/schema.sql ]]; then
        mysql -u $user -D $database < /work/$backend_dir/schema/schema.sql
    fi
    if [[ -f /work/$backend_dir/schema/add_foreign_keys.sql ]]; then
        mysql -u $user -D $database < /work/$backend_dir/schema/add_foreign_keys.sql
    fi
    # load data for test data if any
    if [[ -d /work/$backend_dir/schema/data ]]; then
        cd /work/$backend_dir/schema/data
        cnt=$(ls *.csv 2>/dev/null | wc -l)
        if [ "$cnt" != "0" ]; then
            echo "Loading data files..."
            for d in *.csv
            do
                tab=$(echo $d | cut -d . -f 1 | cut -d - -f 2)
                cat <<EOF | mysql -u $user -D $database
load data local infile "$d"
    into table $tab
    fields terminated by '|';
EOF
            done
        fi
    fi
}


function setup_database_pg() {
    database=$1
    backend_dir=$2
    user=$3
    passwd=$4
    #create database
    psql -U postgres <<EOF
        drop database if exists $database;
        create database $database;
EOF
    #drop create user
    got_user=$(echo "select 1 from pg_user where usename='$user'" | psql -U postgres)
    if [[ ! -z $got_user ]]; then
         echo "drop user $user" | psql -U postgres
    fi

    cat <<EOF | psql -U postgres
create user $user with password '$passwd';

EOF
    psql -U postgres -d $database -c "create extension postgis;"
    #create table
    psql -U postgres -d $database < /work/$backend_dir/schema/gis/schema.sql
    #grant table
    psql -U postgres -d $database -c "grant all on all tables in schema public to pajk;"
    #grant sequence
    psql -U postgres -d $database -c "grant all on all sequences in schema public to pajk";
    #load data
    psql -U postgres -d $database -c "copy district_boundary from
    '/work/$backend_dir/schema/gis/data/district_boundary.csv' using delimiters ',';"
    #remote connection
    sed -i -e 's|#listen_addresses|listen_addresses|' /var/lib/pgsql/9.4/data/postgresql.conf
    #restart
    service postgresql-9.4 restart
}

########## MAIN BLOCK ##########
echo "Setting up banner..."
setup_banner
echo "Setting up pre-requisite softwares..."
setup_pre_requisite_softwares
echo "Setting up database account..."
create_database_user "pajk" "abc"
if [ -d /work/backends/rhino ]; then
    echo "Setting up rhino DB..."
    setup_database "rhino" "backends/rhino" "pajk"
fi
if [ -d /work/backends/workflow ]; then
    echo "Setting up activiti workflow DB..."
    setup_database "workflow" "backends/workflow" "pajk"
fi
if [ -d /work/backends/ac ]; then
    echo "Setting up activationcenter DB..."
    setup_database "activationcenter" "backends/ac" "pajk"
fi
if [ -d /work/backends/camel ]; then
    echo "Setting up address DB..."
    setup_database "address" "backends/camel" "pajk"
    setup_database_pg "addrgis" "backends/camel" "pajk" "abc"
fi
if [ -d /work/backends/cardbin ]; then
    echo "Setting up cardBIN DB..."
    setup_database "cardbin" "backends/cardbin" "pajk"
fi
if [ -d /work/backends/polo ]; then
    echo "Setting up Polo DB..."
    setup_database "polomanager" "backends/polo" "pajk"
fi
if [ -d /work/backends/fundcomm ]; then
    echo "Setting up fundcomm DB..."
    setup_database "fundmanager" "backends/fundcomm" "pajk"
fi
if [ -d /work/backends/macan ]; then
    echo "Setting up Macan DB..."
    setup_database "macan" "backends/macan" "pajk"
fi
if [ -d /work/backends/hippo ]; then
    echo "Setting up Hippo DB..."
    setup_database "h5service" "backends/hippo" "pajk"
fi
if [ -d /work/backends/dingo ]; then
    echo "Setting up Dingo DB..."
    setup_database "dingo" "backends/dingo" "pajk"
fi
if [ -d /work/backends/fitness ]; then
    echo "Setting up Fitness DB..."
    setup_database "fitness" "backends/fitness" "pajk"
fi
if [ -d /work/backends/panther ]; then
    echo "Setting up Panther DB..."
    setup_database "panther" "backends/panther" "pajk"
fi
if [ -d /work/backends/buffalo ]; then
    echo "Setting up Buffalo DB..."
    setup_database "serve" "backends/buffalo" "pajk"
fi
if [ -d /work/backends/ecenter ]; then
    echo "Setting up ecenter DB..."
    setup_database "enterprisecenter" "backends/ecenter" "pajk"
fi
echo "Setting up Pyxis web config..."
setup_pyxis
for sys in $SYSTEMS
do
    if [[ -d /work/backends/${sys} && -f /tmp/${sys}-rest.conf ]]; then
        echo "Setting up ${sys} RESTful web config..."
        setup_webserver "${sys}-rest.conf"
    fi
done

service nginx reload
echo "Setting up startup scripts..."
setup_startup_scripts

# vim: set ai nu nobk expandtab sw=4 tw=72 ts=4 syntax=sh :
